package com.lwl.service;

import com.lwl.common.JSONSerializer;
import com.lwl.common.RpcDecoder;
import com.lwl.common.RpcRequest;
import com.lwl.handler.UserServiceHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements IUserService {

    //客户端需要调用的防范
    @Override
    public String sayHello(String msg) {

        System.out.println("sayHello() -->{}"+msg);
        return "success";
    }

    //创建一个方法启动服务器
    public static void startServer(String ip,int port) throws InterruptedException {
        //创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //创建服务器启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();


        //配置启动引导对象
        serverBootstrap.group(bossGroup,workGroup)
                //设置通道为nio
                .channel(NioServerSocketChannel.class)
                //创建监听器
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        //设置编码
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast( new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        //将自定义的 channelHandler 添加到通道中
                        pipeline.addLast(new UserServiceHandler());

                    }
                });


        //绑定端口号
        ChannelFuture sync = serverBootstrap.bind(8999).sync();
    }

}
